package cn.sccl.dirms.security.controller;

import cn.sccl.common.security.UserDetailsService;
import cn.sccl.dirms.security.model.Role;
import cn.sccl.dirms.security.model.User;
import cn.sccl.dirms.security.model.UserAndRole;
import cn.sccl.dirms.security.model.UserPrincipalDetails;
import cn.sccl.dirms.security.service.AuthorityManager;
import cn.sccl.dirms.security.service.RoleManager;
import cn.sccl.dirms.security.service.UserAndRoleManager;
import cn.sccl.dirms.security.service.UserManager;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xf-cl on 2017/11/21.15:47
 */
@RestController
public class LoginContrioller {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private UserManager userManager;
    @Autowired
    private UserAndRoleManager userAndRoleManager;
    @Autowired
    private RoleManager roleManager;

    @Autowired
    private AuthorityManager authorityManager;

    @Value("${cas.defaultRoleId}")
    private String defaultRoleId;
    @ResponseBody
    @RequestMapping(value = "/login")
    public Object login(HttpServletRequest request,@RequestBody Map map){
        String username = MapUtils.getString(map,"username",null);
        String name = MapUtils.getString(map,"name",null);
        String group = MapUtils.getString(map,"group",null);
        String openid = MapUtils.getString(map,"openid",null);
        String wx_openid = MapUtils.getString(map,"wx_openid",null);
        String password = MapUtils.getString(map,"password","");

        User user = userManager.findByName(username);

        if(password.equalsIgnoreCase("") && null != openid){
            if(user == null) {
                user = new User();
                user.setCardNo(openid);
                user.setName(username);
                user.setUserName(name);
                user.setSex(null);
                user.setUpdateTime(new Timestamp(new Date().getTime()));
                user.setDeleteFlag(false);
                userManager.create(user);
            }else{
                user.setCardNo(openid);
                user.setUserName(name);
                userManager.save(user);
            }

            Map<String,Object> p = new HashMap<>();
            p.put("userId",user.getId());
//            p.put("roleId",defaultRoleId);

            List<UserAndRole> urs;
            try {
                urs = userAndRoleManager.findBy(p);
            } catch (Exception e) {
                urs = null;
            }
            if(urs == null || urs.isEmpty()) {
                UserAndRole ur = new UserAndRole();
                ur.setRoleId(defaultRoleId);
                ur.setUserId(user.getId());
                userAndRoleManager.save(ur);
            }
            try {
                UserPrincipalDetails u = userDetailsService.loadUserByUsername(username);
                request.getSession().setAttribute("user",u);
                return u;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }else{
            if(user == null){
                return null;
            }
            if(!password.equalsIgnoreCase("")){
                if(!user.getPassword().equals(password)){
                    return null;
                }
            }
            UserPrincipalDetails u = null;
            try {
                u = userDetailsService.loadUserByUsername(username);
                request.getSession().setAttribute("user",u);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return u;
        }
    }

    @ResponseBody
    @RequestMapping(value = "/logout")
    public Object logout(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("user",null);
        session.removeAttribute("user");
        session.invalidate();
        Map<String,Object> res = new HashMap<>();
        res.put("success",true);
        res.put("message","注销成功！");
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/isLogin")
    public Object isLogin(HttpServletRequest request){
        HttpSession session = request.getSession();
        boolean isLogin = false;
        UserPrincipalDetails user = (UserPrincipalDetails)session.getAttribute("user");
        if(user != null){
            isLogin = true;
        }
        Map<String,Object> res = new HashMap<>();
        res.put("isLogin",isLogin);
        return res;
    }
    //模拟cas登录 开始
    @RequestMapping(value = "/jump",method = {RequestMethod.POST,RequestMethod.GET})
    public void callback(HttpServletRequest request ,HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String appid = request.getParameter("appid");
        String state = request.getParameter("state");
        System.out.println("账号："+name + "<br>" + "密码："+password+ "<br>" +"appid："+appid+ "<br>" +"state："+state+ "<br>");
        String token = "wo shi token";
//    System.out.println(request.getContextPath()+"/dirms/cas/callback");
        response.sendRedirect(request.getContextPath()+"/dirms/cas/callback?token="+token+"&state="+state);
    }

    @ResponseBody
    @RequestMapping(value = "/ssoapi/v2/checkToken",method = {RequestMethod.POST})
    public Object checkToken(HttpServletRequest request ,HttpServletResponse response,@RequestBody Map<String,String> map) throws IOException {
        String appid = MapUtils.getString(map,"appid","");
        String token = MapUtils.getString(map,"token","");
        String appsecret = MapUtils.getString(map,"appsecret","");
        String userip = MapUtils.getString(map,"userip","");
        System.out.println("appid:"+appid+",token:"+token+",appsecret:"+appsecret+",userip:"+userip);
        String access_token = "wo shi access_token";
        Map<String,Object> res = new HashMap<String,Object>();
        res.put("error",0);
        res.put("message","");
        res.put("openid","openid");
        res.put("access_token",access_token);

        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/oauth/getUserInfo",method = {RequestMethod.POST})
    public Object getUserInfo(HttpServletRequest request ,HttpServletResponse response,@RequestBody Map<String,String> map) throws IOException {
        String access_token = MapUtils.getString(map,"access_token","");
        String openid = MapUtils.getString(map,"openid","");
        System.out.println("access_token:"+access_token+",openid:"+openid);
        Map<String,Object> res = new HashMap<String,Object>();
        res.put("error",0);
        res.put("message","");
        res.put("openid",openid);
        res.put("username","username");
        res.put("name","name");
        res.put("group","group");
        res.put("wx_openid","wx_openid");
        System.out.println(res);
        return res;
    }

    @RequestMapping(value = "/cas/logout",method = {RequestMethod.POST})
    public void caslogout(HttpServletRequest request ,HttpServletResponse response) throws IOException {
        String callback = request.getParameter("callback");
        System.out.println(callback);
        response.sendRedirect(callback);
    }
    //模拟cas登录 结束
}
